//
//  IMDeviceUtils.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/6/23.
//

#import "IMDeviceUtils.h"
#import <UIKit/UIKit.h>
#import <sys/utsname.h>
#import <mach/mach.h>
#import <AdSupport/AdSupport.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>

@implementation IMDeviceUtils

+ (NSString *)deviceUUID {
    static NSString *uuid = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 优先使用IDFA
        if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
            NSUUID *idfa = [[ASIdentifierManager sharedManager] advertisingIdentifier];
            uuid = [idfa UUIDString];
        } else {
            // 使用IDFV作为备选
            NSUUID *idfv = [[UIDevice currentDevice] identifierForVendor];
            uuid = [idfv UUIDString];
        }
        
        // 如果都没有，生成一个随机UUID并存储
        if (!uuid || [uuid isEqualToString:@"00000000-0000-0000-0000-000000000000"]) {
            NSString *stored = [[NSUserDefaults standardUserDefaults] stringForKey:@"IMDeviceUUID"];
            if (stored) {
                uuid = stored;
            } else {
                uuid = [[NSUUID UUID] UUIDString];
                [[NSUserDefaults standardUserDefaults] setObject:uuid forKey:@"IMDeviceUUID"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        }
    });
    return uuid;
}

+ (NSString *)deviceModel {
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    // iPhone型号映射
    static NSDictionary *deviceMap = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        deviceMap = @{
            // iPhone
            @"iPhone1,1": @"iPhone",
            @"iPhone1,2": @"iPhone 3G",
            @"iPhone2,1": @"iPhone 3GS",
            @"iPhone3,1": @"iPhone 4",
            @"iPhone3,2": @"iPhone 4",
            @"iPhone3,3": @"iPhone 4",
            @"iPhone4,1": @"iPhone 4S",
            @"iPhone5,1": @"iPhone 5",
            @"iPhone5,2": @"iPhone 5",
            @"iPhone5,3": @"iPhone 5c",
            @"iPhone5,4": @"iPhone 5c",
            @"iPhone6,1": @"iPhone 5s",
            @"iPhone6,2": @"iPhone 5s",
            @"iPhone7,1": @"iPhone 6 Plus",
            @"iPhone7,2": @"iPhone 6",
            @"iPhone8,1": @"iPhone 6s",
            @"iPhone8,2": @"iPhone 6s Plus",
            @"iPhone8,4": @"iPhone SE",
            @"iPhone9,1": @"iPhone 7",
            @"iPhone9,2": @"iPhone 7 Plus",
            @"iPhone9,3": @"iPhone 7",
            @"iPhone9,4": @"iPhone 7 Plus",
            @"iPhone10,1": @"iPhone 8",
            @"iPhone10,2": @"iPhone 8 Plus",
            @"iPhone10,3": @"iPhone X",
            @"iPhone10,4": @"iPhone 8",
            @"iPhone10,5": @"iPhone 8 Plus",
            @"iPhone10,6": @"iPhone X",
            @"iPhone11,2": @"iPhone XS",
            @"iPhone11,4": @"iPhone XS Max",
            @"iPhone11,6": @"iPhone XS Max",
            @"iPhone11,8": @"iPhone XR",
            @"iPhone12,1": @"iPhone 11",
            @"iPhone12,3": @"iPhone 11 Pro",
            @"iPhone12,5": @"iPhone 11 Pro Max",
            @"iPhone12,8": @"iPhone SE 2",
            @"iPhone13,1": @"iPhone 12 mini",
            @"iPhone13,2": @"iPhone 12",
            @"iPhone13,3": @"iPhone 12 Pro",
            @"iPhone13,4": @"iPhone 12 Pro Max",
            @"iPhone14,2": @"iPhone 13 mini",
            @"iPhone14,3": @"iPhone 13",
            @"iPhone14,4": @"iPhone 13 Pro",
            @"iPhone14,5": @"iPhone 13 Pro Max",
            @"iPhone14,6": @"iPhone SE 3",
            @"iPhone14,7": @"iPhone 14",
            @"iPhone14,8": @"iPhone 14 Plus",
            @"iPhone15,2": @"iPhone 14 Pro",
            @"iPhone15,3": @"iPhone 14 Pro Max",
            @"iPhone15,4": @"iPhone 15",
            @"iPhone15,5": @"iPhone 15 Plus",
            
            // iPad
            @"iPad1,1": @"iPad",
            @"iPad2,1": @"iPad 2",
            @"iPad2,2": @"iPad 2",
            @"iPad2,3": @"iPad 2",
            @"iPad2,4": @"iPad 2",
            @"iPad2,5": @"iPad mini",
            @"iPad2,6": @"iPad mini",
            @"iPad2,7": @"iPad mini",
            @"iPad3,1": @"iPad 3",
            @"iPad3,2": @"iPad 3",
            @"iPad3,3": @"iPad 3",
            @"iPad3,4": @"iPad 4",
            @"iPad3,5": @"iPad 4",
            @"iPad3,6": @"iPad 4",
            @"iPad4,1": @"iPad Air",
            @"iPad4,2": @"iPad Air",
            @"iPad4,3": @"iPad Air",
            @"iPad4,4": @"iPad mini 2",
            @"iPad4,5": @"iPad mini 2",
            @"iPad4,6": @"iPad mini 2",
            @"iPad4,7": @"iPad mini 3",
            @"iPad4,8": @"iPad mini 3",
            @"iPad4,9": @"iPad mini 3",
            @"iPad5,1": @"iPad mini 4",
            @"iPad5,2": @"iPad mini 4",
            @"iPad5,3": @"iPad Air 2",
            @"iPad5,4": @"iPad Air 2",
            
            // Simulator
            @"i386": @"iPhone Simulator",
            @"x86_64": @"iPhone Simulator"
        };
    });
    
    NSString *deviceName = deviceMap[platform];
    return deviceName ?: platform;
}

+ (NSString *)systemVersion {
    return [[UIDevice currentDevice] systemVersion];
}

+ (NSString *)appVersion {
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    return [NSString stringWithFormat:@"%@(%@)", version ?: @"1.0", build ?: @"1"];
}

+ (CGSize)screenSize {
    return [UIScreen mainScreen].bounds.size;
}

+ (BOOL)isPad {
    return [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad;
}

+ (NSUInteger)totalMemory {
    return [NSProcessInfo processInfo].physicalMemory;
}

+ (NSUInteger)availableMemory {
    vm_size_t page_size;
    mach_port_t mach_port = mach_host_self();
    vm_statistics64_data_t vm_stat;
    mach_msg_type_number_t host_size = sizeof(vm_statistics64_data_t) / sizeof(natural_t);
    
    host_page_size(mach_port, &page_size);
    host_statistics64(mach_port, HOST_VM_INFO, (host_info64_t)&vm_stat, &host_size);
    
    return (NSUInteger)(vm_stat.free_count * page_size);
}

+ (NSString *)networkType {
    // 简化的网络类型检测，实际项目中可使用Reachability
    return @"Unknown";
}

+ (NSString *)carrierName {
    return @"Unknown";
}

+ (NSTimeZone *)timeZone {
    return [NSTimeZone localTimeZone];
}

+ (NSString *)languageCode {
    return [NSLocale preferredLanguages].firstObject ?: @"en";
}

+ (NSString *)countryCode {
    return [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode] ?: @"US";
}

+ (NSString *)IDFA {
    if (@available(iOS 14, *)) {
        // iOS 14+ 需要检查ATT权限
        ATTrackingManagerAuthorizationStatus status = [ATTrackingManager trackingAuthorizationStatus];
        if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
            return [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
        } else {
            // 权限未授权，返回nil
            return nil;
        }
    } else {
        // iOS 14以下版本检查广告跟踪是否启用
        if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
            return [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
        } else {
            return nil;
        }
    }
}

+ (NSString *)IDFV {
    NSUUID *idfv = [[UIDevice currentDevice] identifierForVendor];
    return [idfv UUIDString];
}

+ (BOOL)isJailbroken {
    // 检测越狱的多种方法
    NSArray *jailbreakPaths = @[
        @"/Applications/Cydia.app",
        @"/Library/MobileSubstrate/MobileSubstrate.dylib",
        @"/bin/bash",
        @"/usr/sbin/sshd",
        @"/etc/apt",
        @"/private/var/lib/apt/"
    ];
    
    for (NSString *path in jailbreakPaths) {
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            return YES;
        }
    }
    
    // 尝试写入系统目录
    NSError *error;
    NSString *testString = @"ywoeq0rgljb6ydjh";
    [testString writeToFile:@"/private/jailbreak_test.txt" 
                 atomically:YES 
                   encoding:NSUTF8StringEncoding 
                      error:&error];
    if (!error) {
        [[NSFileManager defaultManager] removeItemAtPath:@"/private/jailbreak_test.txt" error:nil];
        return YES;
    }
    
    return NO;
}

+ (NSDictionary *)deviceInfo {
    NSMutableDictionary *info = [@{
        @"uuid": [self deviceUUID],
        @"model": [self deviceModel],
        @"system_version": [self systemVersion],
        @"app_version": [self appVersion],
        @"screen_size": NSStringFromCGSize([self screenSize]),
        @"is_pad": @([self isPad]),
        @"total_memory": @([self totalMemory]),
        @"available_memory": @([self availableMemory]),
        @"language": [self languageCode],
        @"country": [self countryCode],
        @"timezone": [[self timeZone] name],
        @"is_jailbroken": @([self isJailbroken])
    } mutableCopy];
    
    // 添加IDFA（如果可用）
    NSString *idfa = [self IDFA];
    if (idfa) {
        info[@"idfa"] = idfa;
    }
    
    // 添加IDFV（如果可用）
    NSString *idfv = [self IDFV];
    if (idfv) {
        info[@"idfv"] = idfv;
    }
    
    return [info copy];
}

@end
